const mongoose = require('mongoose');

// 数据库连接字符串
const mongoURI = 'mongodb://localhost:27017/MoonBlog';
// 连接到数据库
const connectDB = async () => {
  try {
    await mongoose.connect(mongoURI, {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    });
    console.log('MongoDB Connected...');
  } catch (err) {
    console.error(err.message);
    // 退出进程
    process.exit(1);
  }
};

// 关闭数据库连接
const closeDB = async () => {
  mongoose.connection.close();
};

const initToClose = async (callback) => {
  try {
    await connectDB()
    await callback()
    // await mongoose.connection.close();
  } catch (err) {
    console.log(1111111)
  }
}

module.exports = { connectDB, closeDB, initToClose };